package com.duoqin.feedback.ui;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.duoqin.account.DuoqinAccount;
import com.duoqin.account.data.RefreshTokenResponse;
import com.duoqin.account.viewmodel.LoginViewModel;
import com.duoqin.common.ui.AbsActivity;
import com.duoqin.common.utils.QNHelper;
import com.duoqin.feedback.data.FeedBackResponse;
import com.duoqin.feedback.data.FeedbackRequest;
import com.duoqin.feedback.viewmodel.FeedbackViewModel;
import com.duoqin.syncassistant.R;
import com.duoqin.syncassistant.SyncAssistantApplication;
import com.duoqin.syncassistant.viewmodel.BaseViewModel;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class FeedbackMain extends AbsActivity {

    private LoginViewModel mViewModel;
    private EditText feedbackTitle;
    private EditText feedbackContent;
    private View mProgressView;
    ImageView feedBackImage;
    private FeedbackViewModel feedbackViewModel;
    public final static int HANDLER_UPLOAD_FILE_SUCCESS = 1;
    public final static int HANDLER_UPLOAD_FILE_FAIL = 2;
    private final static int REQUEST_SELECT_GALLERY_IMAGE = 5;
    private String uploadUrl = "";
    private File fileFeedback;
    private ImageView selectResultImage;


    @SuppressLint("HandlerLeak")
    protected Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == HANDLER_UPLOAD_FILE_SUCCESS) {
                uploadUrl = "http://log.duoqin.com/" + fileFeedback.getName();
            } else if (msg.what == HANDLER_UPLOAD_FILE_FAIL) {
                Toast.makeText(FeedbackMain.this, getString(R.string.duoqin_feedback_upload_fail), Toast.LENGTH_LONG).show();
            }
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback_main);
        setupModelObserver();
        setupTitle(getString(R.string.duoqin_feedback_title));
        initView();
        confirmStatus();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.feedback_toolbar_menu, menu);
        return true;
    }


    private void confirmStatus() {
        if (!SyncAssistantApplication.getsInstance().hasLogin()) {
            Intent intent = new Intent(DuoqinAccount.INTENT_ACTION_LOGIN);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setPackage(getPackageName());
            startActivity(intent);
        }else if(SyncAssistantApplication.getsInstance().hasLogin()){
            mViewModel.refreshToken(DuoqinAccount.getAccountToken(getApplicationContext()));
        }
        checkPermissions();
    }


    private void initView() {
        feedbackTitle = findViewById(R.id.duoqin_feedback_edit_title);
        feedbackContent = findViewById(R.id.duoqin_feedback_edit_content);
        mProgressView = findViewById(R.id.login_progress);
        feedBackImage = findViewById(R.id.feedback_image_show);
        selectResultImage = findViewById(R.id.feedback_select_result_image);
        feedBackImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectGalleryImages();
            }
        });
    }


    private void setupModelObserver() {
        feedbackViewModel = ViewModelProviders.of(this).get(FeedbackViewModel.class);

        final Observer<FeedBackResponse> feedBackResponseObserver = new Observer<FeedBackResponse>() {
            @Override
            public void onChanged(@Nullable FeedBackResponse feedBackResponse) {
                showProgress(false);
                if (feedBackResponse != null) {
                    if(feedBackResponse.getErrorCode() == 200){
                        Toast.makeText(FeedbackMain.this,getString(R.string.duoqin_feedback_submit_success),Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(FeedbackMain.this,getString(R.string.duoqin_feedback_submit_fail),Toast.LENGTH_LONG).show();
                    }
                }

            }
        };

        feedbackViewModel.submitData().observe(this, feedBackResponseObserver);

        mViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);

        final Observer<RefreshTokenResponse> refreshTokenResponseObserver =
                new Observer<RefreshTokenResponse>() {
                    @Override
                    public void onChanged(@Nullable final RefreshTokenResponse response) {
                        Log.i(TAG, "onChanged RefreshTokenResponse = " + response);
                        if (response != null) {
                            Log.d(TAG, "onChanged code = " + response.getCode()
                                    + "; msg = " + response.getMsg());
                            Log.d(TAG, "onChanged data = " + response.getData());
                        }
                        if (response != null) {
                            if (BaseViewModel.SERVER_RESULT_SUCCESS == response.getCode()) {
                                if (response.getData() != null) {
                                    SyncAssistantApplication.getsInstance().updateToken(
                                            response.getData().getAccessToken(),
                                            response.getData().getExpiredAt());
                                }
                            } else if (BaseViewModel.SERVER_RESULT_ERROR_INVALID_TOKEN
                                    == response.getCode()) {
                                Toast.makeText(getApplicationContext(),
                                        R.string.error_login_token_expired,
                                        Toast.LENGTH_SHORT).show();
                                SyncAssistantApplication.getsInstance().clearToken();
                            }
                        } else {
                            Log.w(TAG, "refresh token failed");
                        }
                    }
                };
        mViewModel.reFreshTokenResponse().observe(this, refreshTokenResponseObserver);
    }

    private void checkPermissions() {
            List<String> permissionsNeeded = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
                permissionsNeeded.add(Manifest.permission.GET_ACCOUNTS);
            }
            if (permissionsNeeded.size() > 0) {
                requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]),
                        PERMISSIONS_REQUEST_CODE);
            }
    }


    private void selectGalleryImages(){
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent,REQUEST_SELECT_GALLERY_IMAGE);
    }

    private void submit() {
        if (!checkSubmitInfo()) {
            return;
        }
        showProgress(true);
        FeedbackRequest feedbackRequest = new FeedbackRequest();
        feedbackRequest.setContent(feedbackContent.getText().toString());
        String userName = DuoqinAccount.getAccountName(this);
        feedbackRequest.setPhone(userName);
        feedbackRequest.setTimestamp(System.currentTimeMillis());
        feedbackRequest.setTitle(feedbackTitle.getText().toString());
        feedbackRequest.setUrl(uploadUrl);
        feedbackViewModel.requestSubmitFeedback(feedbackRequest);
    }

    private boolean checkSubmitInfo() {

        if (!SyncAssistantApplication.getsInstance().hasLogin()) {
            Toast.makeText(this, R.string.account_not_login, Toast.LENGTH_LONG).show();
            Intent intent = new Intent(DuoqinAccount.INTENT_ACTION_LOGIN);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setPackage(getPackageName());
            startActivity(intent);
            return false;
        }

        if (TextUtils.isEmpty(feedbackTitle.getText().toString())) {
            Toast.makeText(this, R.string.duoqin_feedback_edit_title_tip, Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e("Permissions callback", "Permissions callback");
        if (PERMISSIONS_REQUEST_CODE != requestCode) {
            return;
        }
        if (permissions.length > 0) {
            for (int permissionId = 0; permissionId < permissions.length; permissionId++) {
                if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissions[permissionId])) {
                    if (grantResults.length > permissionId) {
                        if (0 != grantResults[permissionId]) {
                            finish();
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e(TAG, "onActivityResult resultCode = " + resultCode
                + "; requestCode = " + requestCode + "data = " + data);
        if (RESULT_OK != resultCode || data == null) return;
       if(requestCode == REQUEST_SELECT_GALLERY_IMAGE){
            if(data.getData() == null){
                return;
            }
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);

            Objects.requireNonNull(cursor).moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            selectResultImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            fileFeedback = new File(picturePath);
            if(fileFeedback.length() > 15 * 1048576){
                Toast.makeText(this, getString(R.string.duoqin_feedback_file_too_large_tip), Toast.LENGTH_SHORT).show();
                return;
            }
            QNHelper.getsQNInstance(myHandler).uploadFeedbackFile(fileFeedback, fileFeedback.getName());
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_submit) {
            submit();
        }else if(item.getItemId() == android.R.id.home){
            finish();
            return true;
        }
        return true;
    }

    private void showProgress(final boolean show) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    }
}


